package window.tab;

import entity.HotelInfo;
import manage.HotelDBManager;
import window.panel.FilterSortPanel;
import window.component.HotelCard;

import javax.swing.*;
import javax.swing.text.StyledEditorKit;
import java.awt.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class HotelTab extends JPanel {

    String city;
    ArrayList<HotelInfo> hotelList = new ArrayList<>();  // 缓存的酒店列表
    JScrollPane scrollPane;
    GridBagConstraints gbc;
    JPanel hotelListPanel;

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public HotelTab() {
        this.setLayout(new BorderLayout());
        scrollPane = new JScrollPane();
        hotelListPanel = new JPanel();

        // 使用 GridBagLayout 来允许卡片保持大小并自动换行
        hotelListPanel.setLayout(new GridBagLayout());
        gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.NONE;
        gbc.insets = new Insets(10, 10, 10, 10);  // 设置卡片之间的间距
        gbc.anchor = GridBagConstraints.FIRST_LINE_START;
        gbc.weighty = 0;
        gbc.weightx = 1.0;

        scrollPane.setViewportView(hotelListPanel);
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);  // 禁用水平滚动条

        JPanel viewportPanel = new JPanel(new BorderLayout());
        viewportPanel.add(hotelListPanel, BorderLayout.NORTH);
        scrollPane.setViewportView(viewportPanel);

        FilterSortPanel filterSortPanel = new FilterSortPanel();

        city = filterSortPanel.getSelectedCity();

        JButton refreshButton = new JButton("Refresh");
        refreshButton.addActionListener(e -> loadHotels());

        JPanel topPanel = new JPanel();
        topPanel.setLayout(new BorderLayout());
        topPanel.add(refreshButton, BorderLayout.EAST);
        topPanel.add(filterSortPanel, BorderLayout.CENTER);

        this.add(topPanel,BorderLayout.NORTH);
        this.add(scrollPane, BorderLayout.CENTER);

        // 初次加载酒店列表
        loadHotels();

        filterSortPanel.getCityComboBox().addActionListener(e -> {
            String selectedCity = filterSortPanel.getSelectedCity();
            System.out.println("Selected City: " + selectedCity);
            setCity(selectedCity);
            loadHotels();  // 更新酒店列表
            adjustLayout();
        });

        filterSortPanel.getPriceComboBox().addActionListener(e -> {
            String selectedPriceSort = filterSortPanel.getSelectedPriceSort();
            System.out.println("Price Sort: " + selectedPriceSort);
            sortHotelsByPrice(selectedPriceSort);
            adjustLayout();
        });

        filterSortPanel.getStarComboBox().addActionListener(e -> {
            String selectedStarSort = filterSortPanel.getSelectedStarSort();
            System.out.println("Star Sort: " + selectedStarSort);
            sortHotelsByStars(selectedStarSort);
            adjustLayout();
        });

        // 添加监听器以在窗口大小变化时调整卡片布局
        scrollPane.getViewport().addChangeListener(e -> {
            adjustLayout();
        });
    }

    public void loadHotels() {
        hotelListPanel.removeAll(); // 清除所有现有卡片

        // 更新缓存的酒店列表
        hotelList = HotelDBManager.getHotelsByCity(city);

        int columnCount = 3;  // 假设默认情况下一行展示3个卡片
        int index = 0;

        for (HotelInfo hotelInfo : hotelList) {
            HotelCard hotelCard = new HotelCard(hotelInfo, this);
            Dimension cardSize = new Dimension(350, 150);  // 设置卡片的固定大小（固定宽度和高度）
            hotelCard.setPreferredSize(cardSize);
            hotelCard.setMaximumSize(cardSize);
            hotelCard.setMinimumSize(cardSize);

            // 设置 GridBagConstraints 的位置
            gbc.gridx = index % columnCount;  // 当前列
            gbc.gridy = index / columnCount;  // 当前行

            hotelListPanel.add(hotelCard, gbc);
            index++;
        }

        // 刷新界面以确保新添加的组件可见
        hotelListPanel.revalidate();
        hotelListPanel.repaint();
    }

    // 动态调整 hotelListPanel 的卡片布局
    public void adjustLayout() {
        hotelListPanel.removeAll(); // 清除所有卡片

        int cardWidth = 350;  // 使用与原始卡片一致的宽度
        int availableWidth = scrollPane.getViewport().getWidth();  // 可用的宽度
        int columnCount = Math.max(1, availableWidth / (cardWidth + 20));  // 计算可以容纳多少卡片（包含间距）

        int index = 0;
        for (HotelInfo hotelInfo : hotelList) {
            HotelCard hotelCard = new HotelCard(hotelInfo, this);
            Dimension cardSize = new Dimension(cardWidth, 150);  // 保持与原始卡片一致的大小（宽度和高度）
            hotelCard.setPreferredSize(cardSize);
            hotelCard.setMaximumSize(cardSize);
            hotelCard.setMinimumSize(cardSize);

            // 计算新的位置
            gbc.gridx = index % columnCount;  // 当前列
            gbc.gridy = index / columnCount;  // 当前行

            hotelListPanel.add(hotelCard, gbc);
            index++;
        }

        // 刷新 hotelListPanel，以确保界面更新
        hotelListPanel.revalidate();
        hotelListPanel.repaint();
    }

    // 按价格排序酒店列表
    private void sortHotelsByPrice(String selectedPriceSort) {
        if (selectedPriceSort.equals("Low to High")) {
            Collections.sort(hotelList);
        } else if (selectedPriceSort.equals("High to Low")) {
            Collections.sort(hotelList, Collections.reverseOrder());
        }
    }

    // 按星级排序酒店列表
    private void sortHotelsByStars(String selectedStarSort) {
        if (selectedStarSort.equals("Low to High")) {
            Collections.sort(hotelList, Comparator.comparingInt(HotelInfo::getRating));
        } else if (selectedStarSort.equals("High to Low")) {
            Collections.sort(hotelList, (h1, h2) -> Integer.compare(h2.getRating(), h1.getRating()));
        }
    }
}
